Select from multiple tables in Rails - Has Many "articles" through [table_1, table_2]?

Posted by viatropos on Stack Overflow See other posts from Stack Overflow or by viatropos
Published on 2010-12-31T00:34:11Z Indexed on 2010/12/31 0:54 UTC
Read the original article Hit count: 185

Filed under:

I'm in a situation where I need to get all articles that are tied to a User through 2 tables:

  1. article_access: gives users privilege to see an article
  2. article_favorites: of public articles, users have favorited these

So in ActiveRecord you might have this:

class User < ActiveRecord::Base
  has_many :article_access_tokens
  has_many :article_favorites

  def articles
    unless @articles
      ids     = article_access_tokens.all(:select => "article_id").map(&:article_id) + article_favorites.all(:select => "article_id").map(&:article_id)
      @articles  = Article.send(:scoped, :conditions => {:id => ids.uniq})
    end

    @articles
  end
end

That gives me basically an articles association which reads from two separate tables. Question is though, what's the right way to do this?

Can I somehow make 1 SQL SELECT call to do this?

© Stack Overflow or respective owner

Related posts about ruby-on-rails